const koa = require("koa");
const app = new koa();
const Router = require("koa-router");
const router = new Router();
const axios = require("axios");
const cheerio = require("cheerio");
const url = "https://movie.douban.com/top250"
router.get("/",async ctx=>{
    console.log(ctx.request.query);
    let {start} = ctx.request.query
    let html = await axios.get(url);
    if(start == undefined){
        start = 0;
    }
    const $ = cheerio.load(html.data,{
        decodeEntities:false   //解码设置为false,中文不会乱码
    });
    var result = [];
    var items = $(".grid_view .item");
    items.each((index,value)=>{
        var imgUrl = $(value).find(".pic img").attr("src");
        var title = $(value).find(".pic img").attr("alt")
        var labels = $(value).find(".bd p").html().trim().split("<br>")[1].trim().split("/").map(item=>item.trim())
        var rating_num = $(value).find(".star .rating_num").html()
        var evaluate = $(value).find(".star span:last-child").html().replace(/[^\d]/g,"")
        var slogo = $(value).find(".quote .inq").html()
        result.push({
            imgUrl,
            title,
            labels,
            rating_num,
            evaluate,
            slogo
        })
    })
    ctx.body = result;
})
router.get("/subject/:id",async ctx=>{
    console.log(ctx.request.params);
    let {id} = ctx.request.params;
    let url =`https://movie.douban.com/subject/${id}/`;
    let arr=[];
    let html = await axios.get(url);
    const $ = cheerio.load(html.data,{
        decodeEntities:false   //解码设置为false,中文不会乱码
    });
    let item = $("#content h1 span").html();
    let img = $(".nbgnbg img").attr("src");
    let short = $(".short span").html();
    arr.push({
        item,img,short
    })
    ctx.body = arr;
})
app.use(router.routes());
app.listen(8080)
/* 
1.axios抓取豆瓣
2.cheerio解析页面
3.返回数据给前端
 */